//
//  CartInfoDao.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/12.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  购物车Dao

#import "CartInfoDao.h"
#import "FMDatabase.h"
#import "MJExtension.h"
#define TABLENAME @"TB_CART_INFO"
#define PROD_ID @"prodId"
#define CART_INFOS @"cartInfos"
#define PROD_COUNT @"prodCount"

@interface CartInfoDao()
{
    FMDatabase *db;
    NSString *database_path;
}

@end

@implementation CartInfoDao
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [paths objectAtIndex:0];
        database_path = [documents stringByAppendingPathComponent:DB_NAME];
        db = [FMDatabase databaseWithPath:database_path];
        [self createTable];
    }
    return self;
}
/**
 *  创建表
 */
- (void)createTable{
    //sql 语句
    if ([db open]) {
        NSString *sql =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (_id integer primary key autoincrement,'%@' varchar(100),'%@' varchar(100),'%@' INTEGER,key1 varchar(100),key2 varchar(100),key3 varchar(100),key4 varchar(100),key5 varchar(100))",TABLENAME,PROD_ID,CART_INFOS,PROD_COUNT];
        BOOL res = [db executeUpdate:sql];
        if (!res) {
            JXLog(@"error when creating db cart table");
        } else {
            JXLog(@"success to creating db cart table");
        }
        [db close];
    }
}
//判断商品是否已经存在
-(BOOL)isContainsProd:(NSString *)prodId{
    if([db open]){
        NSString *sql = [NSString stringWithFormat:@"SELECT (%@) FROM %@ WHERE %@ = %@",PROD_ID,TABLENAME,PROD_ID,prodId];
        FMResultSet * rs = [db executeQuery:sql];
        if ([rs next]) {
             [db close];
            return YES;
        }
        [db close];
    }
    return NO;
}

//添加单品
-(BOOL)addProd:(NSString *)prodId cartProd:(NSDictionary *)cartProd{
    BOOL result = NO;
    if ([self isContainsProd:prodId]) {//该商品已经存在,更新数量的就可以
       result = [self updateProd:cartProd[@"prodId"] cartProd:cartProd];
    }else{//该商品不存在,需要insert
        if ([db open]) {
            // 把字典对象序列化成NSData二进制数据
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cartProd];
            BOOL result = [db executeUpdate:@"INSERT INTO TB_CART_INFO (prodId,cartInfos,prodCount) VALUES (?,?,?)",cartProd[@"prodId"],data,cartProd[@"prodCount"]];
            if (!result) {
                JXLog(@"insert into a product error for cartinfo table error");
            } else {
                JXLog(@"insert into a product error for cartinfo table success");
            }
            [db close];
        }
    }
    return result;
}

//删除单品
-(BOOL)deleteProd:(NSString *)prodId{
    if ([db open]) {
        BOOL res = [db executeUpdate:@"DELETE FROM TB_CART_INFO WHERE prodId = ?",prodId];
        if (!res) {
            JXLog(@"delete a product error for cartinfo table");
        } else {
            JXLog(@"delete a product success for cartinfo table");
        }
        [db close];
        return res;
    }
    return NO;
}

//删除所有商品
-(BOOL)deleteAllProds{
    if ([db open]) {
        NSString *sql= [NSString stringWithFormat:
                        @"DELETE FROM '%@'",
                        TABLENAME];
        BOOL res = [db executeUpdate:sql];
        if (!res) {
            JXLog(@"delete all product error for cartinfo table");
        } else {
            JXLog(@"delete all product success for cartinfo table");
        }
        [db close];
        return res;
    }
    return NO;
}

//更新单品的信息
-(BOOL)updateProd:(NSString *)prodId cartProd:(NSDictionary *)cartProd{
    if([db open]){
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cartProd];
        
        BOOL res = [db executeUpdate:@"UPDATE TB_CART_INFO SET cartInfos = ? , prodCount = ? WHERE prodId = ?",data,cartProd[@"prodCount"],prodId];
        if (!res) {
            JXLog(@"update product info error for cartinfo table");
        } else {
            JXLog(@"update product info success for cartinfo table");
        }
        [db close];
        return res;
    }
    return NO;
}
//查询商品总数
-(NSInteger)queryProdsCount{
     NSInteger prodsCount = 0;
     if([db open]){
         FMResultSet * rs = [db executeQuery:@"SELECT SUM(prodCount) FROM TB_CART_INFO"];
         if ([rs next]) {
            prodsCount = [rs intForColumnIndex:0];
         }
         [db close];
     }
     return prodsCount;
}

//查询单品数量
-(int)queryProdCount:(NSString *)prodId{
    int prodCount = 0;
    if([db open]){
        FMResultSet * rs = [db executeQuery:@"SELECT (prodCount) FROM TB_CART_INFO WHERE prodId = ?",prodId];
        if ([rs next]) {
            prodCount = [rs intForColumnIndex:0];
        }
        [db close];
    }
    return prodCount;
}

//查询所有商品详细信息
-(NSArray *)findAllProds{
    NSMutableArray *cartInfosArray = [NSMutableArray array];
    if([db open]){
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",TABLENAME];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
             NSData *data = [rs objectForColumnName:CART_INFOS];
             NSDictionary *cartProd = [NSKeyedUnarchiver unarchiveObjectWithData:data];
             CartProdSub *prod = [CartProdSub objectWithKeyValues:cartProd];
            [cartInfosArray addObject:prod];
        }
        [db close];
    }
    return cartInfosArray;
}
@end
